<template>
    <div>
        <TCollapse title="商合采购订单损失情况">
            <el-row :gutter="10" class="marginBottom14" type="flex" justify="start">
                <el-col :span="1.5" style="color: red;">
                    <div v-for="(item, index) in titleList" :key="index"
                        style="display: flex;align-items: center;color: #ff0000;line-height: 18px;margin-bottom: 5px;">
                        {{ item.title }}
                        <el-button v-if="item.showbtn" class="pms-button-primary"
                            @click="clickMaterialClassify">可退至虚拟库物料分类</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-row v-if="this.$route.query.type === 'todo'" :gutter="10" class="marginBottom14" type="flex"
                justify="end">
                <el-col :span="1.5">
                    <div class="main">
                        <!-- <MyForm class="search-form" ref="formRef" v-model="queryParams" :form-option="OrderformOption"
                            :select-list="dicLists" /> -->
                        <el-button v-if="newWorkDetail.activityDefID === 'correct_01'" class="pms-button-primary"
                            @click="updateOrderStatus">更新物资服务订单</el-button>
                    </div>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" type="card" :before-leave="tabLeaveClick">
                <el-tab-pane v-for="item in tabOption" :key="item.name" :label="item.label" :name="item.name">
                    <!-- 物资 -->
                    <MaterialOrder :tableData="materialTableData" :columns="materialColumns"
                        v-if="activeName === 'materialOrderInfo'" :subEditor="subEditor" @changeInput="materialInput"
                        :activeName="activeName" :workDetailsInfo="newWorkDetail" />
                    <!-- 服务 -->
                    <ServiceOrder v-if="activeName === 'serviceOrderInfo'" :tableData="serviceTableData"
                        @changeInput="serviceInput" :columns="serviceColumns" @selectChange="serviceSelectChange"
                        :activeName="activeName" :workDetailsInfo="newWorkDetail" />
                </el-tab-pane>
                <el-row :gutter="10" class="marginBottom14" type="flex" justify="center">
                    <el-col :span="1.5">
                        <el-button v-if="newWorkDetail.activityDefID === 'correct_01'" class="pms-button-primary"
                            style="margin-top: 20px;" @click="saveInfo(true)">保存明细</el-button>
                        <el-button v-if="(showBtnCalc && getBasicDetail.isShowSentSh === '1')"
                            class="pms-button-primary" style="margin-top: 20px;"
                            @click="pushShangHe">特别修正结果推送商合</el-button>
                        <el-button v-if="(showBtnCalc && getBasicDetail.isShowSentSh === '1')"
                            class="pms-button-primary" style="margin-top: 20px;"
                            @click="pushShangHeProgress">推送商合进度</el-button>
                        <el-button
                            v-if="this.$route.query.specalType === 'todo' || (showBtnCalc && getBasicDetail.isShowSentSet === '1')"
                            class="pms-button-primary" style="margin-top: 20px;"
                            @click="getShangHeOrder">获取商合订单并结算送审</el-button>
                        <el-button
                            v-if="this.$route.query.specalType === 'todo' || (showBtnCalc && getBasicDetail.isShowSentFinSet === '1')"
                            class="pms-button-primary" style="margin-top: 20px;"
                            @click="getShangHeCost">获取财务成本单并决算送审</el-button>
                    </el-col>
                </el-row>
                <!-- 按钮 -->
            </el-tabs>
            <el-dialog ref="materialClassification" v-dialogDrag :close-on-click-modal="false"
                :visible.sync="showMaterialClassification" width="70%">
                <div slot="title" class="dialog-header">可退至虚拟库物料分类</div>
                <material-classification v-if="showMaterialClassification" ref="cancelRetreatVisible" />
            </el-dialog>
            <MateriaPop :isShowDilog="isShowMaterialDilog" :urlData="urlData" @closeDialog="closeMaterialDialog" />
        </TCollapse>
    </div>
</template>

<script>
import { isChangeStatus, handleSaveMaterialData, handleSaveServiceData, pushToShangheMessage } from "@/views/speciaCorrection/auxiliary/index"
import { tabOption, titleList, materialColumns, serviceColumns, subEditor, OrderformOption } from '../option'
import materialClassification from '@/views/material/components/materialClassification.vue'
import MaterialOrder from './materiaOrder.vue'
import ServiceOrder from './serviceOrder.vue'
import MyForm from '@/components/basic/myForm'
import MateriaPop from '@/views/balance/materiapop/materiaPop.vue'
import { Mixins } from "@/views/speciaCorrection/minix"
import {
    getSpecialDetail,
    updateOrderStatus,
    getMaterialTableDataApi,
    getServiceTableDataApi,
    saveMaterialInfoApi,
    saveServiceInfoApi,
    checkMaterialBeforeEditApi,
    pushToShangheMaterialApi,
    pushToShangheServiceApi,
    getShangheOrderApi,
    getFinanceOrderApi,
    isChangeSupplierApi
} from "@/api/speciaCorrection/index";
import _ from 'lodash'
export default {
    name: "PurchaseOrderPage",
    components: {
        materialClassification,
        MaterialOrder,
        ServiceOrder,
        MateriaPop,
        MyForm,
    },
    mixins: [Mixins],
    watch: {
        newPrjDetail: {
            handler(val) {
                if (JSON.stringify(val) !== '{}') {
                    this.urlData = { ...this.newPrjDetail, type: this.$route.query.type }
                    this.getSpecialInfo()
                    this.getMaterialTableData()
                }
            },
            deep: true,
            immediate: true
        },
        // 切换tab时重新获取数据
        activeName: {
            handler(val) {
                if (val === 'serviceOrderInfo') {
                    this.getServiceTableData()
                } else {
                    this.getMaterialTableData()
                }
            },
            deep: true
        }
    },
    computed: {
        showBtnCalc() {
            return this.newWorkDetail.activityDefID === 'correct_04'
        }
    },
    data() {
        return {
            subEditor,
            materialColumns,
            serviceColumns,
            tabOption,
            titleList,
            activeName: 'materialOrderInfo',
            showMaterialClassification: false,
            materialTableData: [
            ],
            serviceTableData: [],
            queryParams: {},
            dicLists: {
                PRO_STAGE: [
                    { dictId: '0', dictName: '否' },
                    { dictId: '1', dictName: '是' }]
            },
            OrderformOption,
            getBasicDetail: {},
            // 深拷贝初始化数据
            initDataObj: {
                initMaterialData: [],
                initServiceData: []
            },
            // 保存数据的方法
            saveEnumObj: {
                materialOrderInfo: 'saveMaterialInfo',
                serviceOrderInfo: 'saveServiceInfo'
            },
            isShowMaterialDilog: false,
            urlData: {},
            saveMaterialIdList: [],
            saveServiceIdList: []
        }
    },
    methods: {
        // 获取基本信息
        async getSpecialInfo() {
            const params = {
                prjId: "",
                adjustId: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            };
            const { code, data } = await getSpecialDetail(params);
            if (+code === 200) {
                this.getBasicDetail = data
                this.OrderformOption.itemData.forEach((item) => {
                    item.value = data.isUpdateOrder
                })
                if (this.$refs.formRef !== undefined) {
                    this.$refs.formRef.initData(this.OrderformOption)
                }
            }
        },
        // 获取物资表格数据
        async getMaterialTableData() {
            const params = {
                adjustId: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            };
            const { code, data } = await getMaterialTableDataApi(params)
            if (+code === 200) {
                this.materialTableData = data
                this.initDataObj.initMaterialData = _.cloneDeep(data)
                this.saveMaterialIdList = []
            }
        },
        // 获取服务表格数据
        async getServiceTableData() {
            const params = {
                adjustId: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            };
            const { code, data } = await getServiceTableDataApi(params)
            if (+code === 200) {
                this.serviceTableData = data.map((item, index) => {
                    return {
                        ...item,
                        spcalTagShow: index
                    }
                })
                this.initDataObj.initServiceData = _.cloneDeep(this.serviceTableData)
                this.saveServiceIdList = []
            }
        },
        // 更新采购订单状态
        async updateOrderStatus() {
            const params = {
                prjId: this.newPrjDetail.prjId,
                adjustId: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            };
            this.$confirm('已填写的物资与服务订单调整内容将被删除，是否确认更新？', '系统提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            }).then(async () => {
                const { code } = await updateOrderStatus(params)
                if (+code === 200) {
                    await this.getSpecialInfo()
                    this.$message.success("更新成功")
                    if (this.activeName === 'serviceOrderInfo') {
                        await this.getServiceTableData()
                    } else {
                        await this.getMaterialTableData()
                    }
                }
            }).catch(() => {
                console.log("cancel");
            })
        },
        // tab切换前校验是否保存数据
        async tabLeaveClick() {
            const { materialChangeShow, serviceChangeShow } = isChangeStatus(this.materialTableData, this.serviceTableData, this.initDataObj)
            if (materialChangeShow || serviceChangeShow) {
                const confirmResult = await this.isEditTitle();
                return confirmResult; // true允许切换，false阻止
            }
            return true
        },
        // 修改未保存
        isEditTitle() {
            return new Promise((resolve, reject) => {
                this.$confirm('本次工程量有修改，是否保存本次调整？', '系统提示', {
                    confirmButtonText: '保存',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
                }).then(async () => {
                    await this[this.saveEnumObj[this.activeName]](true)
                    resolve(true);
                }).catch(() => {
                    reject(false)
                });
            });
        },
        // 打开可退至虚拟库物料分类
        clickMaterialClassify() {
            this.showMaterialClassification = true;
        },
        // 物资回传值 处理逻辑
        async materialInput(row, item, saveValue) {
            this.saveMaterialIdList.push(row.id)
            const params = {
                prjId: this.newPrjDetail.prjId,
                categoryCode: row.categoryCode,
                orderProductId: row.orderProductId
            }
            // 前置条件满足辅材调接口是否可以编辑
            if (row.proType === '1' && row.isCheckPayment === '0'&&this.newPrjDetail.buildModes!=='07') {
                const { code, message } = await checkMaterialBeforeEditApi(params)
                if (+code === 200) {
                    handleSaveMaterialData(row, item, saveValue)
                } else {
                    row[item.prop] = saveValue || ''
                    row['spcalflag'] = 1
                    this.$message.error(message)
                }
            } else {
                handleSaveMaterialData(row, item, saveValue)
            }
        },
        // 服务逻辑计算
        serviceInput(row, item, saveValue) {
            this.saveServiceIdList.push(row.id)
            // 考备一份原始数据逻辑
            const _copyRow = this.initDataObj.initServiceData.filter(item_ => item_.spcalTagShow === row.spcalTagShow)[0]
            const softWort = this.newPrjDetail.isNewbusiness === '1' && ['29','25'].includes(this.newPrjDetail.buildModes) 
            handleSaveServiceData(row, item, saveValue, this.serviceTableData, _copyRow,softWort)
        },
        // 服务勾选是否变更供应商
        serviceSelectChange(val, row, prop) {
            const uniqueArr = [...new Set(this.saveServiceIdList)];
            const isSaveList = this.serviceTableData.filter(item => uniqueArr.includes(item.id))
            if (isSaveList.length > 0) {
                this.$confirm('物资订单明细有未保存的修改，是否继续？', '系统提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
                }).then(async () => {
                    await this.saveServiceInfo(true)
                }).catch(() => {
                    console.log("cancel");
                    row['ifChangeSer'] = row['ifChangeSer'] ? "0" : "1"
                });
                return
            }
            if (row['ifChangeSer']) {
                row['status'] = "1";
                row['changeStatus'] = "6";
            } else {
                row['status'] = "0";
                row['changeStatus'] = "7";
            }
            const params = {
                ...row,
                ifChangeSer: row['ifChangeSer'] ? "1" : "0"
            }
            isChangeSupplierApi(params).then(({ code }) => {
                if (+code === 200) {
                    this.getServiceTableData()
                }
            }).finally(() => {
                this.getServiceTableData()
            })
        },
        // 保存明细
        async saveInfo(type) {
            await this[this.saveEnumObj[this.activeName]](type)
        },
        // 保存物资信息
        async saveMaterialInfo(type) {
            // 去重编辑的重复ID
            const uniqueArr = [...new Set(this.saveMaterialIdList)];
            const isSaveList = this.materialTableData.filter(item => (+item.status) === 1 || uniqueArr.includes(item.id))
            // 保存前正则校验
            // 真保存
            if (isSaveList.length > 0) {
                const { code } = await saveMaterialInfoApi(isSaveList)
                if(+code!==200){
                    throw ""
                }
                if (+code === 200 && type) {
                    this.$message.success("保存成功");
                    this.getMaterialTableData()
                }
                return
            }
            // 假保存
            if (type) {
                this.$message.success("保存成功");
            }
        },
        // 保存服务信息
        async saveServiceInfo(type) {
            // 去重编辑的重复ID
            const uniqueArr = [...new Set(this.saveServiceIdList)];
            const isSaveList = this.serviceTableData.filter(item => (+item.status) === 1 || uniqueArr.includes(item.id))
            // 真保存
            if (isSaveList.length > 0) {
                const { code } = await saveServiceInfoApi(isSaveList)
                if(+code!==200){
                    throw ""
                }
                if (+code === 200 && type) {
                    this.$message.success("保存成功");
                    this.getServiceTableData()
                }
                return
            }
            if (type) {
                this.$message.success("保存成功");
            }
        },
        // 关闭物资子项目绑定弹框
        closeMaterialDialog() {
            this.isShowMaterialDilog = false
        },
        // 特别修正结果推送商合
        async pushShangHe() {
            // 推送之前先获取最新状态
            await this.getSpecialInfo()
            const { isPush, pushMsg, equipCount, servCount } = this.getBasicDetail
            const { promptMsg, pushState } = pushToShangheMessage(isPush, pushMsg, +equipCount, +servCount)
            //推送失败
            if (pushState === "0") {
                this.$confirm(`${promptMsg},是否继续推送？`, '系统提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
                }).then(async () => {
                    // 推送服务
                    await this.pushShangHeService()
                }).catch(() => {
                    console.log("cancel");
                })
            }
            //推送中
            if (pushState === "2") {
                this.$message({
                    message: "交易系统正在进行合同信息校验及数据处理，过程中请点击【推送商合进度】按钮查看进度",
                    type: 'warning'
                })
            }
            // //推送服务成功，然后推送物资
            if (['1', '4'].includes(pushState)) {
                await this.pushShangHeMaterail()
            }

            //推送服务
            if (pushState === "3") {
                await this.pushShangHeService()
            }

            //未调整
            if (['5'].includes(pushState)) {
                this.$message({
                    message: promptMsg,
                    type: 'warning'
                })
            }
        },
        // 物资商合推送
        async pushShangHeMaterail() {
            const params = {
                prjId: this.newPrjDetail.prjId,
                bizseq: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            }
            const { code } = await pushToShangheMaterialApi(params)
            if (+code === 200) {
                await this.pushShangHe()
                 this.$message({
                    message: `推送成功`,
                    type: 'success'
                })
            }
        },
        // 服务商合推送
        async pushShangHeService() {
            const params = {
                prjId: this.newPrjDetail.prjId,
                bizseq: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            }
            const { code } = await pushToShangheServiceApi(params)
            if (+code === 200) {
                await this.pushShangHe()
            }
        },
        // 推送商合进度
        async pushShangHeProgress() {
            const { isPush, pushMsg, equipCount, servCount } = this.getBasicDetail
            const { promptMsg } = pushToShangheMessage(isPush, pushMsg, +equipCount, +servCount)
            this.$message({
                message: `${promptMsg}`,
                type: 'warning'
            })
        },
        // 获取商合订单并结算送审
        async getShangHeOrder() {
            const params = {
                prjId: this.newPrjDetail.prjId,
                bizseq: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            }
            const { code, message } = await getShangheOrderApi(params)
            if (+code === 5555) {
                // 让弹框显示  校验不通过才能显示弹框
                this.$alert(`${message}`, '系统提示', {
                    confirmButtonText: '确定',
                    // 将字符串html化
                    dangerouslyUseHTMLString: true,
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary',
                    callback: action => {
                        this.isShowMaterialDilog = true
                    }
                })
            }
            // 成功跳转到结算送审
            if (+code === 200) {
                this.$message({
                    message: `${message}`,
                    type: 'success'
                })
                // 跳转到结算送审页面
                window.open(`${process.env.VUE_APP_ZHONGRUAN_URL}specialCorrectionSendReview?prjId=${this.newPrjDetail.prjId}&adjustId=${this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId}&workItemId=${this.$route.query.workItemId}&type=${this.$route.query.workItemId ? 'todo' : '1'}`, '_blank')
            }
            if (+code !== 200 && +code !== 5555) {
                this.$message({
                    message: message || '操作异常',
                    type: 'error',
                     dangerouslyUseHTMLString: true,
                })
            }
        },
        // 获取财务成本单并决算送审
        async getShangHeCost() {
            const params = {
                prjId: this.newPrjDetail.prjId,
                bizseq: this.newWorkDetail?.bizObject?.bizSeq || this.$route.query.adjustId,
            }
            const { code } = await getFinanceOrderApi(params)
            if (+code === 200) {
                // 跳转决算送审页面
                window.open(`${process.env.VUE_APP_ZHONGRUAN_URL}handleFinalAccounts?prjId=${this.newPrjDetail.prjId}&bizSeq=${params.bizseq}&type=1&status=1`, '_blank')
            }
        }
    },
}

</script>
<style lang="scss" scoped>
::v-deep .el-tabs__header {
    margin: 0 0 0 0;
}

.main {
    width: 100%;
    display: flex;
    align-items: center;
    position: relative;
    justify-content: right;

    .search-form {
        width: 192px;
        margin-right: 0;
    }
}

.main ::v-deep .el-row {
    width: 200px;
    height: 28px;
}

.main ::v-deep .btnBox {
    z-index: 1;
}

.main ::v-deep .pms-details .el-form-item__content .el-select--mini .el-input__inner {
    padding: 0px 8px;
}

.main ::v-deep .el-input__suffix {
    right: -3px;
}
</style>